<template>
  <div class="location-container">
    <!-- 顶部操作栏 -->
    <el-card shadow="hover" class="operation-card">
      <div class="operation-header">
        <h2 class="page-title">{{ pageTitle }}</h2>
        <div class="operation-buttons">
          <div class="left-buttons">
            <el-button v-if="submitButtonShow" :loading="buttonLoading" type="info" class="operation-btn" @click="submitForm('draft')">
              <el-icon><Document /></el-icon>{{ draftButtonText }}
            </el-button>
            <el-button v-if="submitButtonShow" :loading="buttonLoading" type="primary" class="operation-btn" @click="submitForm('submit')">
              <el-icon><Check /></el-icon>{{ submitButtonText }}
            </el-button>
            <el-button v-if="approvalButtonShow" :loading="buttonLoading" type="success" class="operation-btn" @click="approvalVerifyOpen">
              <el-icon><Stamp /></el-icon>审批
            </el-button>
            <el-button v-if="showApprovalRecord" type="warning" class="operation-btn" @click="handleApprovalRecord">
              <el-icon><Timer /></el-icon>流程进度
            </el-button>
          </div>
          <el-button class="back-btn" @click="goBack()">
            <el-icon><Back /></el-icon>返回
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 主要内容区域 -->
    <el-card shadow="hover" class="content-card">
      <template #header>
        <div class="content-header">
          <span class="section-title">站点信息</span>
        </div>
      </template>

      <el-form
        ref="locationFormRef"
        v-loading="loading"
        :disabled="routeParams.type === 'view'"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="location-form"
      >
        <!-- 基本信息部分 -->
        <div class="form-section">
          <el-row :gutter="24">
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="设备" prop="deviceId">
                <el-select
                  v-if="routeParams.type === 'add'"
                  v-model="form.deviceId"
                  placeholder="请选择设备"
                  class="custom-select"
                  filterable
                  @change="handleDeviceChange"
                >
                  <el-option
                    v-for="device in deviceList"
                    :key="device.id"
                    :label="`${device.deviceName} (${device.deviceNo}) - ${device.model || '未知型号'}`"
                    :value="device.id"
                    :disabled="device.hasLocation"
                  >
                    <div class="device-option">
                      <div class="device-row1">
                        <span class="device-name" :title="device.deviceName">{{ device.deviceName }}</span>
                        <span class="device-no" :title="device.deviceNo">（{{ device.deviceNo }}）</span>
                        <template v-if="device.hasLocation || device.status === 3 || device.status === 1 || device.status === 5">
                          <el-tag class="device-unavailable-tag" size="small" type="danger">
                            {{
                              device.hasLocation
                                ? '已分配'
                                : device.status === 3
                                  ? '故障'
                                  : device.status === 1
                                    ? '离线'
                                    : device.status === 5
                                      ? '作废'
                                      : '不可用'
                            }}
                          </el-tag>
                        </template>
                      </div>
                      <div class="device-row2">
                        <el-tag size="small" type="info" class="device-tag">{{ device.model || '未知型号' }}</el-tag>
                        <el-tag size="small" :type="getDeviceStatusType(device.status)" class="device-tag">
                          {{ getDeviceStatusLabel(device.status) }}
                        </el-tag>
                      </div>
                    </div>
                  </el-option>
                </el-select>
                <div v-else class="device-info-display">
                  <div class="device-basic-info">
                    <el-input v-model="form.deviceName" disabled class="custom-input">
                      <template #prefix>
                        <el-tag size="small" type="info">设备名称</el-tag>
                      </template>
                    </el-input>
                  </div>
                  <div class="device-detail-info">
                    <el-descriptions :column="2" border>
                      <el-descriptions-item label="设备编号">{{ form.deviceNo }}</el-descriptions-item>
                      <el-descriptions-item label="设备型号">{{ form.model }}</el-descriptions-item>
                      <el-descriptions-item label="序列号">{{ form.sn }}</el-descriptions-item>
                      <el-descriptions-item label="通道数">{{ form.channelCount }}</el-descriptions-item>
                      <el-descriptions-item label="设备状态">
                        <el-tag :type="getDeviceStatusType(form.deviceStatus)">
                          {{ getDeviceStatusLabel(form.deviceStatus) }}
                        </el-tag>
                      </el-descriptions-item>
                      <el-descriptions-item v-if="form.imgUrl" label="设备图片">
                        <el-image style="width: 50px; height: 50px" :src="form.imgUrl" :preview-src-list="[form.imgUrl]" fit="cover" />
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="站点状态">
                <el-tag :type="getStatusType(form.status)" size="large" class="status-tag">
                  {{ getStatusLabel(form.status) }}
                </el-tag>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 位置信息部分 -->
        <div class="form-section">
          <el-divider content-position="left" class="section-divider">位置信息</el-divider>

          <el-form-item label="位置名称" prop="location">
            <el-input v-model="form.location" placeholder="请输入位置名称" class="custom-input" />
          </el-form-item>

          <el-form-item label="详细地址" prop="address">
            <el-input
              v-model="form.address"
              type="textarea"
              :rows="3"
              placeholder="请输入详细地址"
              class="custom-textarea"
              @blur="handleAddressBlur"
            />
          </el-form-item>

          <el-form-item label="经纬度" prop="coordinates">
            <el-input v-model="coordinates" placeholder="经度,纬度" readonly class="custom-input">
              <template #append>
                <el-button @click="showMapDialog">选择位置</el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item v-show="false" label="经度" prop="longitude">
            <el-input v-model="form.longitude" placeholder="请输入经度" readonly />
          </el-form-item>
          <el-form-item v-show="false" label="纬度" prop="latitude">
            <el-input v-model="form.latitude" placeholder="请输入纬度" readonly />
          </el-form-item>
        </div>
      </el-form>
    </el-card>

    <!-- 提交组件 -->
    <submitVerify ref="submitVerifyRef" :task-variables="taskVariables as any" @submit-callback="submitCallback" />
    <!-- 审批记录 -->
    <approvalRecord ref="approvalRecordRef" />

    <!-- 地图选择对话框 -->
    <el-dialog v-model="mapDialogVisible" title="选择位置" width="800px" append-to-body destroy-on-close>
      <div class="map-search">
        <el-input v-model="searchKeyword" placeholder="请输入地址搜索" @keyup.enter="handleSearch">
          <template #append>
            <el-button @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
      </div>
      <div class="map-tools">
        <el-button-group>
          <el-button :type="mapType === '3D' ? 'primary' : ''" @click="switchMapType('3D')">3D</el-button>
          <el-button :type="mapType === '2D' ? 'primary' : ''" @click="switchMapType('2D')">2D</el-button>
          <el-button :type="mapType === 'satellite' ? 'primary' : ''" @click="switchMapType('satellite')">卫星</el-button>
        </el-button-group>
        <el-button-group>
          <el-button :type="showDetails ? 'primary' : ''" @click="toggleDetails">
            {{ showDetails ? '隐藏细节' : '显示细节' }}
          </el-button>
        </el-button-group>
      </div>
      <div ref="mapContainer" class="map-container"></div>
      <template #footer>
        <div class="dialog-footer">
          <el-checkbox v-model="autoCompleteAddress">自动补全地址</el-checkbox>
          <el-button type="primary" @click="confirmLocation">确 定</el-button>
          <el-button @click="handleMapDialogClose">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="LocationEdit" lang="ts">
import { addLocation, getLocation, updateLocation, listLocation } from '@/api/vending/location';
import { geocode, regeocode, getLocationByIp } from '@/api/vending/map';
import type { LocationForm, LocationVo } from '@/api/vending/location/types';
import { getlistDevice } from '@/api/vending/device';
import type { DeviceVO } from '@/api/vending/device/types';
import { startWorkFlow } from '@/api/workflow/task';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import { StartProcessBo } from '@/api/workflow/workflowCommon/types';
import { Document, Check, Stamp, Timer, Back } from '@element-plus/icons-vue';
import { ref, getCurrentInstance, onMounted, nextTick, computed } from 'vue';
import type { FormInstance } from 'element-plus';
import { useRoute } from 'vue-router';

// 声明高德地图类型
declare global {
  interface Window {
    AMap: any;
  }
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();

// 基础状态
const buttonLoading = ref(false);
const loading = ref(true);
const deviceList = ref<DeviceVO[]>([]);

// 路由参数
interface RouteParams {
  type: 'add' | 'update' | 'view' | 'approval';
  id?: number;
  taskId?: string;
}

const routeParams = ref<RouteParams>({
  type: 'add'
});

// 表单参数
const initFormData: LocationForm = {
  id: undefined,
  deviceId: undefined,
  deviceName: undefined,
  deviceNo: undefined,
  model: undefined,
  sn: undefined,
  channelCount: undefined,
  imgUrl: undefined,
  location: undefined,
  address: undefined,
  longitude: undefined,
  latitude: undefined,
  status: 3, // 默认设置为待审核状态
  remark: undefined,
  createTime: undefined,
  updateTime: undefined,
  createBy: undefined,
  updateBy: undefined,
  createDept: undefined,
  deviceStatus: undefined
};

const form = ref<LocationForm>({ ...initFormData });

// 地图相关变量
const mapDialogVisible = ref(false);
const mapType = ref('3D');
const showDetails = ref(false);
const searchKeyword = ref('');
const autoCompleteAddress = ref(true);
const mapLoaded = ref(false);
const originalAddress = ref('');
const originalLongitude = ref<number | undefined>();
const originalLatitude = ref<number | undefined>();
let map: any = null;
let marker: any = null;
let satelliteLayer: any = null;

// 预加载地图脚本
const preloadMapScript = () => {
  if (!window.AMap && !document.querySelector('script[src*="amap.com/maps"]')) {
    const script = document.createElement('script');
    script.src = `https://webapi.amap.com/maps?v=2.0&key=44f91bca5fc95f3e79620c2d50bbfaed&plugin=AMap.Geocoder,AMap.Geolocation,AMap.PlaceSearch,AMap.ToolBar,AMap.Scale,AMap.HawkEye,AMap.MapType`;
    script.async = true;
    script.onload = () => {
      console.log('高德地图加载完成');
      mapLoaded.value = true;
    };
    document.head.appendChild(script);
  }
};

// 初始化函数
const initializeComponent = async () => {
  try {
    const query = proxy.$route.query as unknown as RouteParams;
    routeParams.value = {
      type: query.type || 'add',
      id: query.id ? Number(query.id) : undefined,
      taskId: query.taskId as string
    };
    reset();
    loading.value = false;
    await getDeviceList();
    if (
      routeParams.value.type === 'update' ||
      routeParams.value.type === 'add' ||
      routeParams.value.type === 'view' ||
      routeParams.value.type === 'approval'
    ) {
      await getInfo();
    }
  } catch (error) {
    console.error('初始化失败:', error);
    proxy.$modal.msgError('初始化失败');
  }
};

// 生命周期钩子
onMounted(() => {
  // 预加载地图脚本
  preloadMapScript();

  // 其他初始化逻辑
  nextTick(() => {
    initializeComponent();
  });
});

// 添加样式
const style = document.createElement('style');
style.textContent = `
  .info-window {
    padding: 8px;
    min-width: 200px;
  }
  .info-window h4 {
    margin: 0 0 8px 0;
    font-size: 14px;
    color: #333;
  }
  .info-window p {
    margin: 4px 0;
    font-size: 12px;
    color: #666;
  }
  .nearby-list {
    margin-top: 8px;
    border-top: 1px solid #eee;
    padding-top: 8px;
  }
  .nearby-item {
    margin: 8px 0;
    padding: 4px 0;
    border-bottom: 1px dashed #eee;
  }
  .nearby-item:last-child {
    border-bottom: none;
  }
  .nearby-item h5 {
    margin: 0 0 4px 0;
    font-size: 13px;
    color: #333;
  }
  .nearby-item p {
    margin: 2px 0;
    font-size: 12px;
    color: #666;
  }
`;
document.head.appendChild(style);

// 提交组件
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
// 审批记录组件
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();

const locationFormRef = ref<FormInstance>();

const submitFormData = ref<StartProcessBo>({
  businessKey: '',
  tableName: '',
  variables: {}
});
const taskVariables = ref<Record<string, any>>({});

const rules = {
  deviceId: [{ required: true, message: '设备不能为空', trigger: 'change' }],
  location: [{ required: true, message: '位置名称不能为空', trigger: 'blur' }],
  address: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }]
};

// 地图相关
const mapContainer = ref<HTMLElement>();

// 经纬度显示
const coordinates = computed(() => {
  if (form.value.longitude && form.value.latitude) {
    return `${form.value.longitude},${form.value.latitude}`;
  }
  return '';
});

/** 获取设备列表 */
async function getDeviceList() {
  try {
    const res = await getlistDevice({
      pageNum: 1,
      pageSize: 999
    });
    if (res && res.code === 200 && Array.isArray(res.data)) {
      // 获取所有已分配位置的设备
      const locationRes = await listLocation({
        pageNum: 1,
        pageSize: 999
      });
      const locatedDeviceIds = new Set((locationRes.rows || []).map((item: any) => item.deviceId));

      // 标记设备是否已有位置
      deviceList.value = res.data.map((device: any) => ({
        ...device,
        hasLocation: locatedDeviceIds.has(device.id)
      }));
      // console.log(deviceList.value)
    }
  } catch (error) {
    console.error('获取设备列表失败:', error);
    ElMessage.error('获取设备列表失败');
  }
}

// 计算属性：获取可选择的设备列表
const availableDevices = computed(() => {
  return deviceList.value.filter((device: any) => !device.hasLocation || device.id === form.value.deviceId);
});

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  // 新增时设置默认值
  if (routeParams.value.type === 'add') {
    form.value.status = 3; // 设置为待审核
  }
  locationFormRef.value?.resetFields();
};

/** 获取详情 */
const getInfo = () => {
  loading.value = true;
  buttonLoading.value = false;
  nextTick(async () => {
    try {
      if (routeParams.value.type === 'add') {
        // 新增时重置表单
        reset();
        return;
      }
      const res = await getLocation(routeParams.value.id);
      console.log(res.data);
      if (res && res.data) {
        // 处理设备信息
        const deviceInfo = res.data.device || {};
        const locationInfo = {
          ...res.data,
          status: res.data.status || 3,
          deviceName: deviceInfo.deviceName || '',
          deviceNo: deviceInfo.deviceNo || '',
          model: deviceInfo.model || '',
          imgUrl: deviceInfo.imgUrl || '',
          sn: deviceInfo.sn || '',
          channelCount: deviceInfo.channelCount || 0,
          deviceStatus: deviceInfo.status || 0
        };

        // 更新表单数据
        Object.assign(form.value, locationInfo);
        console.log(form.value);
      }
    } catch (error) {
      console.error('获取站点信息失败:', error);
      ElMessage.error('获取站点信息失败');
    } finally {
      loading.value = false;
      buttonLoading.value = false;
    }
  });
};

/** 提交按钮文本 */
const submitButtonText = computed(() => {
  switch (routeParams.value.type) {
    case 'add':
      return '提交审核';
    case 'update':
      return '提交审核';
    default:
      return '提交';
  }
});

/** 提交按钮 */
const submitForm = async (status: string) => {
  try {
    await locationFormRef.value?.validate();
    buttonLoading.value = true;
    let res;
    // 只保留后端允许的字段
    const submitData = {
      id: form.value.id,
      deviceId: form.value.deviceId,
      location: form.value.location,
      address: form.value.address,
      longitude: form.value.longitude,
      latitude: form.value.latitude,
      status: status === 'draft' ? 2 : 3, // 草稿状态为2，提交审核状态为3
      remark: form.value.remark,
      createTime: form.value.createTime,
      updateTime: form.value.updateTime
    };

    if (form.value.id) {
      res = await updateLocation(submitData);
    } else {
      res = await addLocation(submitData);
    }
    form.value = res.data;
    if (status === 'draft') {
      // console.log(res.data);
      buttonLoading.value = false;
      proxy?.$modal.msgSuccess('暂存成功');
      proxy.$tab.closePage(proxy.$route);
      proxy.$router.go(-1);
    } else {
      await handleStartWorkFlow(res.data);
    }
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('提交失败');
  } finally {
    buttonLoading.value = false;
  }
};

// 提交申请
const handleStartWorkFlow = async (data: LocationVo) => {
  try {
    submitFormData.value.tableName = 'device_location';
    submitFormData.value.businessKey = data.id?.toString() || '';
    // 流程变量
    taskVariables.value = {
      entity: data
    };
    submitFormData.value.variables = taskVariables.value;
    const resp = await startWorkFlow(submitFormData.value);
    if (submitVerifyRef.value) {
      buttonLoading.value = false;
      submitVerifyRef.value.openDialog(resp.data.taskId);
    }
  } finally {
    buttonLoading.value = false;
  }
};

// 审批记录
const handleApprovalRecord = () => {
  approvalRecordRef.value.init(form.value.id);
};

// 提交回调
const submitCallback = async () => {
  await proxy.$tab.closePage(proxy.$route);
  proxy.$router.go(-1);
};

// 返回
const goBack = () => {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.go(-1);
};

// 审批
const approvalVerifyOpen = async () => {
  locationFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const submitData = {
        id: form.value.id,
        deviceId: form.value.deviceId,
        location: form.value.location,
        address: form.value.address,
        longitude: form.value.longitude,
        latitude: form.value.latitude,
        status: form.value.status,
        remark: form.value.remark
      };
      await updateLocation({
        ...submitData
      });
      submitVerifyRef.value.openDialog(routeParams.value.taskId);
    }
  });
};

// 校验提交按钮是否显示
const submitButtonShow = computed(() => {
  // 新增或编辑草稿时显示提交按钮
  if (routeParams.value.type === 'add') return true;
  if (routeParams.value.type === 'update' && form.value.status === 2) return true;
  return false;
});

// 校验审批按钮是否显示
const approvalButtonShow = computed(() => {
  // 只有在审批模式下且状态为待审核时才显示审批按钮
  return routeParams.value.type === 'approval' && form.value.status === 3;
});

// 修改流程进度按钮显示逻辑
const showApprovalRecord = computed(() => {
  // 非新增且非草稿状态时显示流程进度
  return form.value && form.value.id && form.value.status !== 2 && ['view', 'approval'].includes(routeParams.value.type);
});

// 页面标题
const pageTitle = computed(() => {
  const type = routeParams.value.type;
  switch (type) {
    case 'add':
      return '新增站点';
    case 'view':
      return '查看站点';
    case 'update':
      return form.value?.status === 2 ? '修改站点' : '编辑站点';
    case 'approval':
      return '审批站点';
    default:
      return '站点管理';
  }
});

// 状态处理函数
const getStatusType = (status: number) => {
  switch (status) {
    case 1:
      return 'info'; // 撤销
    case 2:
      return 'warning'; // 草稿
    case 3:
      return 'warning'; // 待审核
    case 4:
      return 'success'; // 已完成
    case 5:
      return 'danger'; // 已作废
    case 6:
      return 'danger'; // 已退回
    case 7:
      return 'danger'; // 已终止
    default:
      return 'info';
  }
};

const getStatusLabel = (status: number) => {
  switch (status) {
    case 1:
      return '已撤销';
    case 2:
      return '草稿';
    case 3:
      return '待审核';
    case 4:
      return '已完成';
    case 5:
      return '已作废';
    case 6:
      return '已退回';
    case 7:
      return '已终止';
    default:
      return '未知状态';
  }
};

// 添加设备状态处理函数
const getDeviceStatusType = (status: number) => {
  switch (status) {
    case 0:
      return 'info'; // 未使用
    case 1:
      return 'warning'; // 离线
    case 2:
      return 'success'; // 在线
    case 3:
      return 'danger'; // 故障
    case 4:
      return 'warning'; // 维护中
    case 5:
      return 'info'; // 待维护
    default:
      return 'info';
  }
};

const getDeviceStatusLabel = (status: number) => {
  switch (status) {
    case 0:
      return '未使用';
    case 1:
      return '离线';
    case 2:
      return '在线';
    case 3:
      return '故障';
    case 4:
      return '维护中';
    case 5:
      return '待维护';
    default:
      return '未知状态';
  }
};

// 添加设备选择变化处理方法
const handleDeviceChange = (deviceId: number) => {
  const selectedDevice = deviceList.value.find((device) => device.id === deviceId);
  if (selectedDevice) {
    form.value.deviceName = selectedDevice.deviceName;
    form.value.deviceNo = selectedDevice.deviceNo;
    form.value.model = selectedDevice.model;
    form.value.sn = selectedDevice.sn;
    form.value.channelCount = selectedDevice.channelCount;
    form.value.imgUrl = selectedDevice.imgUrl;
  }
};

// 添加地址输入框失焦处理方法
const handleAddressBlur = async () => {
  if (!form.value.address) return;

  try {
    const response = await geocode(form.value.address);
    if (response.data) {
      form.value.longitude = response.data.longitude;
      form.value.latitude = response.data.latitude;
    }
  } catch (error) {
    console.error('地址解析失败:', error);
  }
};

// 修改 showMapDialog 方法
const showMapDialog = () => {
  mapDialogVisible.value = true;
  // 保存原始数据
  originalAddress.value = form.value.address || '';
  originalLongitude.value = form.value.longitude;
  originalLatitude.value = form.value.latitude;
  nextTick(() => {
    initMap();
  });
};

// 地图相关方法
const switchMapType = (type: '3D' | '2D' | 'satellite') => {
  mapType.value = type;
  if (!map) return;

  // 清除之前的卫星图层
  if (satelliteLayer) {
    map.remove(satelliteLayer);
    satelliteLayer = null;
  }

  switch (type) {
    case '3D':
      // 使用标准3D样式
      map.setMapStyle('amap://styles/normal');
      map.setPitch(45);
      map.setFeatures(['bg', 'road', 'building', 'point']);
      // 设置3D建筑
      map.setLayers([
        new window.AMap.TileLayer(),
        new window.AMap.Buildings({
          zooms: [3, 20],
          opacity: 1,
          heightFactor: 1.5
        })
      ]);
      break;
    case '2D':
      // 使用标准2D地图样式
      map.setMapStyle('amap://styles/normal');
      map.setPitch(0);
      map.setFeatures(['bg', 'road', 'point']);
      map.setLayers([new window.AMap.TileLayer()]);
      break;
    case 'satellite':
      // 使用卫星地图样式
      map.setMapStyle('amap://styles/whitesmoke');
      map.setPitch(0);
      map.setFeatures(['bg', 'road', 'point']);
      // 添加卫星图层
      satelliteLayer = new window.AMap.TileLayer.Satellite();
      map.add(satelliteLayer);
      break;
  }
  // 重新设置地图中心点和缩放级别
  const center = map.getCenter();
  const zoom = map.getZoom();
  map.setCenter(center);
  map.setZoom(zoom);
};

/** 切换细节显示 */
function toggleDetails() {
  showDetails.value = !showDetails.value;
  if (!map) return;

  if (showDetails.value) {
    // 显示所有细节
    map.setFeatures(['bg', 'road', 'building', 'point']);
  } else {
    // 隐藏部分细节，但保持3D建筑
    map.setFeatures(['bg', 'road', 'building']);
  }
}

/** 搜索位置 */
function handleSearch() {
  if (!searchKeyword.value) return;

  // 使用地理编码服务搜索位置
  geocode(searchKeyword.value).then((response) => {
    if (response.data) {
      const { longitude, latitude } = response.data;
      form.value.longitude = longitude;
      form.value.latitude = latitude;
      form.value.address = response.data.address;
      updateMarker(longitude, latitude);
      // 搜索后放大到更近的级别
      map.setZoom(17);
    } else {
      proxy.$modal.msgError('未找到该地址');
    }
  });
}

/** 确认选择位置 */
function confirmLocation() {
  if (!form.value.longitude || !form.value.latitude) {
    proxy.$modal.msgError('请先选择位置');
    return;
  }

  if (autoCompleteAddress.value) {
    // 获取详细地址信息
    regeocode(Number(form.value.longitude), Number(form.value.latitude))
      .then((response) => {
        if (response.data) {
          const { province, city, district, formattedAddress, poi, streetNumber } = response.data;

          // 解析街道门牌号信息
          let streetInfo = '';
          if (streetNumber) {
            try {
              const streetNumberObj = JSON.parse(streetNumber);
              streetInfo = `${streetNumberObj.street}${streetNumberObj.number}`;
            } catch (e) {
              console.error('解析街道门牌号失败:', e);
            }
          }

          // 设置位置名称为省市区，过滤掉空值
          const locationParts = [province, city, district].filter((part) => part && part !== '[]');
          form.value.location = locationParts.join('') || formattedAddress;

          // 设置详细地址，包含POI和街道门牌号信息
          let detailAddress = formattedAddress;
          if (poi) {
            detailAddress = detailAddress.replace(poi, '').trim();
          }
          if (streetInfo) {
            detailAddress = `${detailAddress}${streetInfo}`;
          }
          form.value.address = detailAddress;

          mapDialogVisible.value = false;
        } else {
          proxy.$modal.msgError('获取地址信息失败');
        }
      })
      .catch((error) => {
        proxy.$modal.msgError('获取地址信息失败：' + error.message);
      });
  } else {
    mapDialogVisible.value = false;
  }
}

/** 更新标记点 */
function updateMarker(lng: number, lat: number) {
  if (!map) return;

  // 如果已存在标记点，先移除
  if (marker) {
    marker.setMap(null);
  }

  // 创建新的标记点
  marker = new window.AMap.Marker({
    position: [lng, lat],
    map: map,
    animation: 'AMAP_ANIMATION_DROP',
    offset: new window.AMap.Pixel(-13, -30),
    icon: new window.AMap.Icon({
      size: new window.AMap.Size(25, 34),
      image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
      imageSize: new window.AMap.Size(25, 34)
    }),
    label: {
      content: '当前位置',
      direction: 'top',
      offset: new window.AMap.Pixel(10, 25)
    }
  });

  map.setCenter([lng, lat]);
  map.setZoom(17);
}

// 修改 handleMapDialogClose 方法
const handleMapDialogClose = () => {
  mapDialogVisible.value = false;
  // 恢复原始数据
  form.value.address = originalAddress.value;
  form.value.longitude = originalLongitude.value;
  form.value.latitude = originalLatitude.value;
  setTimeout(() => {
    if (map) {
      map.destroy();
      map = null;
    }
    if (marker) {
      marker.setMap(null);
      marker = null;
    }
    if (satelliteLayer) {
      map?.remove(satelliteLayer);
      satelliteLayer = null;
    }
    searchKeyword.value = '';
  }, 300);
};

// 修改 initMap 方法
function initMap() {
  if (!mapContainer.value) return;

  // 清除之前的卫星图层
  if (satelliteLayer) {
    map.remove(satelliteLayer);
    satelliteLayer = null;
  }

  // 创建地图实例
  map = new window.AMap.Map(mapContainer.value, {
    zoom: 15,
    center: [116.397428, 39.90923],
    viewMode: '3D', // 默认使用3D模式
    pitch: 45, // 默认俯仰角为45度
    mapStyle: 'amap://styles/normal', // 使用标准样式
    features: ['bg', 'road', 'building', 'point'],
    dragEnable: true,
    zoomEnable: true,
    jogEnable: true,
    animateEnable: true,
    keyboardEnable: true,
    doubleClickZoom: true,
    scrollWheel: true,
    touchZoom: true,
    showLabel: true,
    layers: [
      new window.AMap.TileLayer(),
      new window.AMap.Buildings({
        zooms: [3, 20],
        opacity: 1,
        heightFactor: 1.5
      })
    ]
  });

  // 添加地图控件
  map.plugin(
    ['AMap.ToolBar', 'AMap.Scale', 'AMap.HawkEye', 'AMap.MapType', 'AMap.PlaceSearch', 'AMap.ControlBar', 'AMap.TileLayer.Satellite', 'AMap.Text'],
    () => {
      // 添加工具条控件
      const toolBar = new window.AMap.ToolBar({
        position: {
          top: '10px',
          right: '10px'
        },
        ruler: true,
        direction: true,
        locate: true,
        liteStyle: false
      });
      map.addControl(toolBar);

      // 添加比例尺控件
      map.addControl(
        new window.AMap.Scale({
          position: 'LB'
        })
      );

      // 添加鹰眼控件
      map.addControl(
        new window.AMap.HawkEye({
          isOpen: true,
          position: 'RB',
          mapStyle: 'amap://styles/normal'
        })
      );

      // 添加3D控件
      map.addControl(
        new window.AMap.ControlBar({
          position: {
            top: '10px',
            left: '10px'
          },
          showZoomBar: true,
          showControlButton: true
        })
      );

      // 添加IP定位按钮
      const ipLocationButton = document.createElement('div');
      ipLocationButton.className = 'amap-ip-location';
      ipLocationButton.innerHTML = '<button class="el-button el-button--primary el-button--small">IP定位</button>';
      ipLocationButton.style.position = 'absolute';
      ipLocationButton.style.top = '10px';
      ipLocationButton.style.right = '120px';
      ipLocationButton.style.zIndex = '100';
      mapContainer.value.appendChild(ipLocationButton);

      // 添加IP定位点击事件
      ipLocationButton.addEventListener('click', () => {
        const ip = window.location.hostname;
        getLocationByIp(ip)
          .then((response) => {
            if (response.data) {
              const { swPoint, nePoint, address } = response.data;
              const [swLng, swLat] = swPoint.split(',').map(Number);
              const [neLng, neLat] = nePoint.split(',').map(Number);

              // 清除之前的矩形区域和文本
              const overlays = map.getAllOverlays();
              overlays.forEach((overlay) => {
                if (overlay instanceof window.AMap.Rectangle || overlay instanceof window.AMap.Text) {
                  map.remove(overlay);
                }
              });

              // 创建矩形区域
              const rectangle = new window.AMap.Rectangle({
                bounds: new window.AMap.Bounds([swLng, swLat], [neLng, neLat]),
                strokeColor: '#FF0000',
                strokeWeight: 2,
                strokeOpacity: 0.8,
                fillColor: '#FF0000',
                fillOpacity: 0.2,
                extData: {
                  name: address
                },
                bubble: true,
                clickable: true
              });

              map.add(rectangle);

              // 添加区域文本
              const text = new window.AMap.Text({
                position: new window.AMap.LngLat((swLng + neLng) / 2, (swLat + neLat) / 2),
                text: address,
                offset: new window.AMap.Pixel(0, 0),
                style: {
                  padding: '5px',
                  backgroundColor: '#fff',
                  borderColor: '#FF0000',
                  borderWidth: '1px',
                  borderRadius: '3px',
                  fontSize: '12px',
                  color: '#333'
                },
                bubble: true,
                clickable: true
              });
              map.add(text);

              // 调整地图视野以包含整个区域
              map.setBounds(rectangle.getBounds());

              // 更新表单地址
              form.value.address = address;
            } else {
              proxy.$modal.msgError('IP定位失败');
            }
          })
          .catch((error) => {
            proxy.$modal.msgError('IP定位失败：' + error.message);
          });
      });
    }
  );

  // 添加点击事件
  map.on('click', (e: any) => {
    const { lng, lat } = e.lnglat;
    form.value.longitude = lng;
    form.value.latitude = lat;
    updateMarker(lng, lat);

    // 清除矩形区域和文本，但保留标记点
    const overlays = map.getAllOverlays();
    overlays.forEach((overlay) => {
      if (overlay instanceof window.AMap.Rectangle || overlay instanceof window.AMap.Text) {
        map.remove(overlay);
      }
    });

    // 逆地理编码
    regeocode(lng, lat).then((response) => {
      if (response.data) {
        form.value.address = response.data.address;
      }
    });
  });

  // 如果已有坐标，则定位到该位置
  if (form.value.longitude && form.value.latitude) {
    updateMarker(Number(form.value.longitude), Number(form.value.latitude));
  }
}

// 修改暂存按钮文本
const draftButtonText = computed(() => {
  switch (routeParams.value.type) {
    case 'add':
      return '暂存草稿';
    case 'update':
      return '暂存草稿';
    default:
      return '暂存';
  }
});
</script>

<style lang="scss" scoped>
.location-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .operation-card {
    margin-bottom: 24px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .operation-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;

      .page-title {
        margin: 0;
        font-size: 22px;
        font-weight: 600;
        color: #303133;
        position: relative;
        padding-left: 12px;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 4px;
          height: 20px;
          background-color: #409eff;
          border-radius: 2px;
        }
      }

      .operation-buttons {
        display: flex;
        gap: 16px;

        .left-buttons {
          display: flex;
          gap: 12px;
        }

        .operation-btn {
          display: flex;
          align-items: center;
          gap: 6px;
          padding: 10px 20px;
          border-radius: 6px;
          transition: all 0.3s;

          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          }

          .el-icon {
            font-size: 16px;
          }
        }

        .back-btn {
          display: flex;
          align-items: center;
          gap: 6px;
          padding: 10px 20px;
          border-radius: 6px;
          transition: all 0.3s;

          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          }
        }
      }
    }
  }

  .content-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .content-header {
      padding: 16px 0;

      .section-title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
        position: relative;
        padding-left: 12px;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 4px;
          height: 18px;
          background-color: #409eff;
          border-radius: 2px;
        }
      }
    }
  }

  .location-form {
    padding: 24px;

    .form-section {
      background-color: #fff;
      border-radius: 8px;
      padding: 24px;
      margin-bottom: 24px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

      .section-divider {
        margin: 32px 0;

        :deep(.el-divider__text) {
          font-size: 16px;
          font-weight: 500;
          color: #606266;
          background-color: #fff;
          padding: 0 16px;
        }
      }
    }

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #606266;
      padding-right: 16px;
    }

    .custom-input,
    .custom-select,
    .custom-date-picker {
      width: 100%;

      :deep(.el-input__wrapper) {
        box-shadow: 0 0 0 1px #dcdfe6 inset;
        border-radius: 6px;
        transition: all 0.3s;
        padding: 0 12px;

        &:hover {
          box-shadow: 0 0 0 1px #409eff inset;
        }

        &.is-focus {
          box-shadow: 0 0 0 1px #409eff inset;
        }
      }
    }

    .custom-textarea {
      :deep(.el-textarea__inner) {
        box-shadow: 0 0 0 1px #dcdfe6 inset;
        border-radius: 6px;
        transition: all 0.3s;
        padding: 12px;

        &:hover {
          box-shadow: 0 0 0 1px #409eff inset;
        }

        &:focus {
          box-shadow: 0 0 0 1px #409eff inset;
        }
      }
    }

    .status-tag {
      width: 100%;
      text-align: center;
      padding: 10px 0;
      border-radius: 6px;
      font-size: 14px;
      font-weight: 500;
    }

    .warning-text {
      color: #f56c6c;
      margin-left: 8px;
      font-size: 13px;
    }
  }
}

:deep(.el-card__header) {
  padding: 16px 24px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

:deep(.el-card__body) {
  padding: 24px;
}

// 地图相关样式
.map-search {
  margin-bottom: 16px;
}

.map-tools {
  margin-bottom: 16px;
  display: flex;
  gap: 16px;
}

.map-container {
  height: 500px;
  border-radius: 8px;
  overflow: hidden;
}

// 添加响应式布局
@media screen and (max-width: 768px) {
  .location-container {
    padding: 16px;

    .operation-header {
      flex-direction: column;
      gap: 16px;

      .operation-buttons {
        width: 100%;
        flex-direction: column;

        .left-buttons {
          flex-direction: column;
          width: 100%;

          .operation-btn {
            width: 100%;
          }
        }

        .back-btn {
          width: 100%;
        }
      }
    }

    .location-form {
      padding: 16px;

      .form-section {
        padding: 16px;
      }

      :deep(.el-form-item) {
        margin-bottom: 20px;
      }

      :deep(.el-form-item__label) {
        float: none;
        display: block;
        text-align: left;
        padding: 0 0 8px;
        line-height: 1.5;
      }

      :deep(.el-form-item__content) {
        margin-left: 0 !important;
      }

      .custom-input,
      .custom-select,
      .custom-date-picker {
        width: 100%;
      }

      .status-tag {
        width: 100%;
        margin-top: 8px;
      }
    }

    .device-info-display {
      .device-detail-info {
        :deep(.el-descriptions) {
          padding: 12px;

          .el-descriptions__label {
            width: 80px;
            padding: 12px 8px;
            font-size: 13px;
          }

          .el-descriptions__content {
            padding: 12px 8px;
            font-size: 13px;
          }

          .el-descriptions__cell {
            padding: 0;
          }

          .el-descriptions__body {
            .el-descriptions__table {
              .el-descriptions__cell {
                padding: 0;
              }
            }
          }
        }
      }
    }
  }
}

.device-option {
  padding: 2px 0 1px 0;
  min-width: 320px;
  display: flex;
  // min-height: 200px;
  flex-direction: column;
  justify-content: center;
}
.el-select-dropdown__list li {
  height: 100%;
  padding: 2px 20px;
}
.device-row1 {
  display: flex;
  align-items: center;
  font-size: 14px;
  font-weight: 600;
  color: #222;
  line-height: 20px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.device-name {
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.device-no {
  font-size: 13px;
  color: #b0b0b0;
  font-weight: 400;
  margin-left: 6px;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.device-row2 {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 2px;
  min-height: 18px;
}
.device-tag {
  height: 18px;
  line-height: 16px;
  font-size: 12px;
  padding: 0 8px;
  border-radius: 8px;
  background: #f4f8fb;
  color: #409eff;
  border: none;
  white-space: nowrap;
}
:deep(.el-select-dropdown__item) {
  padding: 2px 8px;
  height: auto;
  min-height: unset;
  line-height: normal;
  text-align: left;
  transition: background 0.2s;
  border-radius: 4px;
  margin: 1px 0;
  font-size: 13px;
  &:hover,
  &.hover {
    background: #f0f7ff;
  }
  &.selected {
    background: #e6f7ff;
    .device-row1 {
      color: #409eff;
    }
  }
}
.device-unavailable-tag {
  margin-left: 12px;
  height: 18px;
  line-height: 16px;
  font-size: 12px;
  padding: 0 8px;
  border-radius: 8px;
  background: #ffeaea;
  color: #f56c6c;
  border: none;
  white-space: nowrap;
}
</style>
